<?php

/**
 * EmsVideo form.
 *
 * @package    ems1
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class EmsVideoForm extends BaseEmsVideoForm
{
    public function configure()
    {
        unset ($this['content_id']);

        $this->setWidget('file', new sfWidgetFormInputHidden());

        $this->setValidator('file',new sfValidatorString(array('required' => false)));

        $this->setWidget('file_type', new sfWidgetFormInputHidden());

        $this->setValidator('file_type',new sfValidatorString(array('max_length' => 100, 'required' => false)));

        $this->setWidget('file_size', new sfWidgetFormInputHidden());

        $this->setValidator('file_size',new sfValidatorInteger(array('required' => false)));

        $this->setWidget('tmp_file', new sfWidgetFormInputFile());

        $this->setValidator('tmp_file',new sfValidatorString(array('required' => false)));

        $this->widgetSchema->setLabels(
            array(
                'tmp_file'    => 'Video'
            ));

        if($this->getObject()->exists() && $this->getObject()->getFile()){
            $file = $this->getObject()->getFile();

            $folder = sfConfig::get('sf_upload_dir').'/portal_'.$this->getOption('portal_id').'/videos/';

            if(is_file($folder.$file)){
                $file_size = filesize($folder.$file);

                $this->setDefaults(array('file_size' => $file_size));
            } else {
                $this->setDefaults(array('file_size' => 0));
            }
        }
    }
    
    protected function doUpdateObject($values)
    {
        if(strcasecmp($values['file'],'') != 0){

            $path_parts_file = pathinfo($values['file']);

            $folder = sfConfig::get('sf_upload_dir').'/portal_'.$this->getOption('portal_id');

            if(!$this->getObject()->exists() || strcasecmp($path_parts_file['basename'], $this->getObject()->getFile()) != 0){
                $values['file'] = $this->saveUploadedFile(
                                    $path_parts_file['basename'],
                                    $values['file_type'],
                                    $values['file'],
                                    $values['file_size'],
                                    $folder.'/videos/'
                                );
            }
        }

        unset(
            $values['file_type'], $values['file_size'], $values['tmp_file']
        );

        parent::doUpdateObject($values);
    }

    protected function saveUploadedFile($originalName, $type, $tempName, $size, $path) {

        $validated_file = new sfValidatedFile($originalName, $type, $tempName, $size, $path);

        return $validated_file->save();
    }
}
